<?php

namespace App\Store\Services\Goods;

use App\Store\Models\Account\SiteStore;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\Goods\GoodsStockin;
use App\Store\Models\Goods\GoodsStockinInfolist;
use App\Store\Models\Goods\GoodsStockList;
use App\Store\Models\Order\OrderSalesGoods;
use App\Store\Validate\Goods\GoodsStockin as ValidateGoodsGoodsStockin;
use Illuminate\Http\Request;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Financial\Goods\GoodsWarning;
use App\Store\Models\Goods\GoodsChangeLog;
use App\Store\Models\Goods\GoodsLog;
use Illuminate\Support\Facades\DB;
use function Symfony\Component\Translation\t;

class Goods
{
    /**
     * 商品修改日志写入
     * 用于记录商品信息修改前后的日志，包括修改人信息、修改时间等，
     * 便于追溯商品信息的变化历史。
     *
     * @param Request $request 当前请求对象，用于获取用户信息等
     * @param string $order_sncode 订单编号
     * @param array $goodsinfo 商品基本信息，包括商品编号、店铺编号等
     * @param array $beforedata 商品修改前的信息
     * @param array $afterdata 商品修改后的信息
     * @param int $start_store_id 初始化店铺ID，如果不提供，则默认为商品所属店铺ID
     * @return void
     */
    public static function changeGoodsLog(Request $request, $order_sncode, $goodsinfo, $beforedata, $afterdata, $start_store_id = 0)
    {
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $data = [
            'cp_id' => $cp_id,
            'start_store_id' => $start_store_id > 0 ? $start_store_id : $goodsinfo['store_id'],
            'store_id' => $goodsinfo['store_id'],
            'order_sncode' => $order_sncode,
            'goods_sn_code' => $goodsinfo['goods_sn_code'],
            'beforedata' => $beforedata,
            'afterdata' => $afterdata,
            'create_account_id' => $accountinfo['id'],
            'create_account_real_name' => $accountinfo['real_name'],
            'create_at' => time(),
            'update_at' => time(),
            'remark' => $goodsinfo['remark']
        ];
        GoodsChangeLog::create($data);
    }

    /**
     * 获取商品是否预警
     */
    public static function checkGoodsWarning($goodsinfo)
    {
        // $winfo=GoodsWarning::where(['cp_id'=>$goodsinfo['cp_id'],'store_id'=>$goodsinfo['store_id'],'goods_category_id'=>$goodsinfo['goods_category_id'],'goods_style_id'=>$goodsinfo['goods_style_id']])->first();
        // if(!$winfo){
        //     return 1;
        // }
        // if($goodsinfo['goods_count']<$winfo['warning_stock']){
        //     return 2;
        // }
        // return 1;

        $winfo = GoodsWarning::where(['is_del' => 1, 'cp_id' => $goodsinfo['cp_id'], 'store_id' => $goodsinfo['store_id'], 'goods_category_id' => $goodsinfo['goods_category_id'], 'goods_style_id' => $goodsinfo['goods_style_id']])
            ->where([['warning_at', '>', 0]])->first();
        if (!$winfo) {
            return 1;//未预警
        }
        return 2;
    }

    /**
     * 记录商品日志
     *
     * @param Request $request 请求对象，用于获取当前账号信息
     * @param int $start_store_id 起始店铺ID
     * @param int $target_store_id 目标店铺ID
     * @param array $goodsinfo 商品信息数组，包含商品的各种属性
     * @param int $count 商品数量
     * @param int $log_type 日志类型---类型入库：1入库，2加库存，3减库存，4编辑;调拨：5撤审，11调拨入库，12调拨出库，13取消调拨;返厂：21返厂出库，22取消返厂，23返厂入库;销售相关：91销售出库，92销售取消，93退货上柜，94取消上柜
     * @param string $with_sn_code 是否包含订单序列号，默认为空字符串
     * @return void
     */
    public static function goodsLog(Request $request, int $start_store_id, int $target_store_id, array $goodsinfo, int $count, int $log_type, $with_sn_code = '')
    {
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $start_store_id = $start_store_id > 0 ? $start_store_id : intval($accountinfo['store_ids'] ?? 0);

        if (in_array($log_type, [1, 2])) {
            $start_store_id = 0;
        } elseif (in_array($log_type, [21, 23, 5])) {
            $target_store_id = 0;
        }

        $data = [
            'cp_id' => $cp_id,
            'start_store_id' => $start_store_id,
            'target_store_id' => $target_store_id,
            'goods_img' => isset($goodsinfo['goods_img']) ? $goodsinfo['goods_img'] : '',
            'goods_sn_code' => $goodsinfo['goods_sn_code'],
            'goods_name' => $goodsinfo['goods_name'] ?? '',
            'goods_category_id' => $goodsinfo['goods_category_id']??0,
            'cf_no' => isset($goodsinfo['cf_no']) ? $goodsinfo['cf_no'] : '',
            'count' => $count,
            'piece_weight' => isset($goodsinfo['piece_weight']) ? $goodsinfo['piece_weight'] : 0,
            'netglod_weight' => (isset($goodsinfo['is_code_more']) && $goodsinfo['is_code_more'] == 2) ? (isset($goodsinfo['total_netglod_weight']) ? $goodsinfo['total_netglod_weight'] : 0) : (isset($goodsinfo['netglod_weight']) ? $goodsinfo['netglod_weight'] : 0),
            'label_price' => isset($goodsinfo['label_price']) ? $goodsinfo['label_price'] : 0,
            'piececost_fee' => isset($goodsinfo['piececost_fee']) ? $goodsinfo['piececost_fee'] : 0,
            'log_type' => $log_type,
            'with_sn_code' => $with_sn_code,
            'stockin_at' => $goodsinfo['stockin_at']??0,
            'create_account_id' => $accountinfo['id'],
            'create_account_real_name' => $accountinfo['real_name'],
            'create_at' => time(),
            'update_at' => time(),
            'is_code_more' => isset($goodsinfo['is_code_more']) ? $goodsinfo['is_code_more'] : 1,
            'costgram_fee' => $goodsinfo['costgram_fee'] ?? 0,
            'costpiece_fee' => $goodsinfo['costpiece_fee'] ?? 0,
            'costglod_price' => $goodsinfo['costglod_price'] ?? 0,
            'total_cost_fee'=>$goodsinfo['total_cost_fee'] ?? 0,
        ];

        info('商品流水' . $log_type, $data);
        GoodsLog::create($data);

    }


    public static function goodsLogSales(Request $request, int $start_store_id, int $target_store_id, array $goodsinfo, int $count, int $log_type, $with_sn_code = '')
    {
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $start_store_id = intval($accountinfo['store_ids'] ?? 0);
        $data = [
            'cp_id' => $cp_id,
            'start_store_id' => $start_store_id,
            'target_store_id' => $target_store_id,
            'goods_img' => isset($goodsinfo['goods_img']) ? $goodsinfo['goods_img'] : '',
            'goods_sn_code' => $goodsinfo['goods_sn_code'],
            'goods_name' => $goodsinfo['goods_name'],
            'goods_category_id' => $goodsinfo['goods_category_id']??0,
            'cf_no' => isset($goodsinfo['cf_no']) ? $goodsinfo['cf_no'] : '',
            'count' => $count,
            'piece_weight' => isset($goodsinfo['piece_weight']) ? $goodsinfo['piece_weight'] : 0,
            'netglod_weight' => isset($goodsinfo['weight']) ? $goodsinfo['weight'] : 0,
            'label_price' => isset($goodsinfo['label_price']) ? $goodsinfo['label_price'] : 0,
            'piececost_fee' => isset($goodsinfo['piececost_fee']) ? $goodsinfo['piececost_fee'] : 0,
            'log_type' => $log_type,
            'with_sn_code' => $with_sn_code,
            'stockin_at' => $goodsinfo['stockin_at']??0,
            'create_account_id' => $accountinfo['id'],
            'create_account_real_name' => $accountinfo['real_name'],
            'create_at' => time(),
            'update_at' => time(),
            'is_code_more' => isset($goodsinfo['is_code_more']) ? $goodsinfo['is_code_more'] : 1,
            'costgram_fee' => $goodsinfo['costgram_fee'] ?? 0,
            'costpiece_fee' => $goodsinfo['costpiece_fee'] ?? 0,
            'costglod_price' => $goodsinfo['costglod_price'] ?? 0,
            'total_cost_fee'=>$goodsinfo['total_cost_fee'] ?? 0,
        ];

        info('商品订单流水' . $log_type, $data);
        GoodsLog::create($data);

    }

    /**
     * 新增商品入库
     * @param $infodata
     * @param $accountinfo
     * @param $source
     * @return true
     * @throws \Exception
     */
    public function stockInAdd($infodata, $accountinfo, $source = 1)
    {
        $cp_id = $accountinfo['cp_id'];
        $storeinfo = SiteStore::where(['id' => $infodata['store_id'], 'cp_id' => $cp_id])->first();
        if (!$storeinfo) {
            return throw new \Exception('无效门店参数');
        }
        $isRepeatRes = $this->isRepeatGoodsSnCode(['goods_sn_code' => $infodata['goods_sn_code'], 'cp_id' => $cp_id]);
        if ($isRepeatRes['code'] == '001') {
            return throw new \Exception($isRepeatRes['msg']);
        }
        $maindata = [];
        $maindata['cp_id'] = $cp_id;
        $maindata['store_id'] = $infodata['store_id'];
        $maindata['order_sncode'] = StoreCommon::createOrderSn();
        $maindata['goods_count'] = $infodata['count'];
        $maindata['supply_id'] = isset($infodata['supply_id']) ? $infodata['supply_id'] : 0;
        $maindata['goods_brand_id'] = isset($infodata['goods_brand_id']) ? intval($infodata['goods_brand_id']) : 0;
        $maindata['paymoney'] = isset($infodata['paymoney']) ? $infodata['paymoney'] : 0;
        $maindata['create_at'] = time();
        $maindata['update_at'] = time();
        $maindata['create_account_id'] = $accountinfo['id'];
        $maindata['create_account_real_name'] = $accountinfo['real_name'];


        $categoryinfo = GoodsCategory::where(['cp_id' => $cp_id, 'store_id' => $infodata['store_id'], 'is_del' => 1, 'id' => $infodata['goods_category_id']])->first();
        if (!$categoryinfo) {
            return throw new \Exception('无效分类参数');
        }
        if ($infodata['is_code_more'] == 2 && $categoryinfo->is_gram == 2) {
            return throw new \Exception('该分类为非克重商品，不可选择一码多货');
        }

        $infodata['stockin_at'] = empty($infodata['stockin_at']) ? time() : $infodata['stockin_at'];
        $infodata['procure_at'] = empty($infodata['procure_at']) ? time() : $infodata['procure_at'];
        $infodata['order_sncode'] = $maindata['order_sncode'];

        info('商品入库新增参数', $infodata);
        // 是否一码多货：1否，2是
        if ($infodata['is_code_more'] == 2) {
            if (!isset($infodata['total_netglod_weight']) || $infodata['total_netglod_weight'] <= 0) {
                return throw new \Exception('一码多货必须输入总金重');
            }
            $infodata['total_netglod_weight_new'] = $infodata['total_netglod_weight'] ?? 0;
            $infodata['total_cost_fee'] = bcmul(($infodata['costglod_price'] ?? 0), $infodata['total_netglod_weight']);
        } else {
            // 总件重
            $infodata['total_piece_weight'] = isset($infodata['piece_weight']) ? doubleval($infodata['piece_weight'] * $infodata['count']) : 0;
            $infodata['total_piece_weight_new'] = isset($infodata['piece_weight']) ? $infodata['piece_weight'] * $infodata['count'] : 0;;
            // 总金重
            $infodata['total_netglod_weight'] = isset($infodata['netglod_weight']) ? doubleval($infodata['netglod_weight'] * $infodata['count']) : 0;
            $infodata['total_netglod_weight_new'] = $infodata['total_netglod_weight'];
            $is_gram = GoodsCategory::where(['cp_id' => $cp_id, 'is_del' => 1, 'store_id' => $infodata['store_id'], 'id' => $infodata['goods_category_id']])->value('is_gram');
            if ($is_gram == 1) {
                if ($infodata['total_netglod_weight'] <= 0 || $infodata['netglod_weight'] <= 0) {
                    return throw new \Exception('总金重以及金重不可小于0');
                }
                $infodata['total_cost_fee'] = bcmul((string)(($infodata['costgram_fee'] ?? 0) + ($infodata['costglod_price'] ?? 0)), $infodata['total_netglod_weight'], 0) + ($infodata['costpiece_fee'] ?? 0) * $infodata['count'];
            } else {
                $infodata['piece_weight'] = isset($infodata['piece_weight']) ? doubleval($infodata['piece_weight']) : 0;
                if ($infodata['total_piece_weight'] < 0 || $infodata['piece_weight'] < 0) {
                    return throw new \Exception('总件重以及件重不可小于0');
                }

                $infodata['total_cost_fee'] = ($infodata['piececost_fee'] ?? 0) * $infodata['count'];
            }
        }

        //处理数据类型
        $infodata['cp_id'] = $cp_id;
        foreach ($infodata as $key => $val) {
            if ($val == '' || $val == 0) {
                unset($infodata[$key]);
            } else {
                if ($key == 'piece_weight') {
                    $infodata['piece_weight_new'] = $infodata['piece_weight'];
                }
                if ($key == 'netglod_weight') {
                    $infodata['netglod_weight_new'] = $infodata['netglod_weight'];
                }
                if ($key == 'label_price') {
                    $infodata['label_price_new'] = $infodata['label_price'];
                }
            }
        }
        // 如果是商品入口直接添加默认为审核通过
        if ($source == 2) {
            // 主表
            $maindata['audit_status'] = 3;
            $maindata['audit_at'] = time();

            // 附表
            $infodata['audit_status'] = 2;
            $infodata['audit_at'] = time();
        }

        DB::beginTransaction();
        try {
            $pid = GoodsStockin::query()->create($maindata)->id;
            $infodata['p_id'] = $pid;
            GoodsStockinInfolist::query()->create($infodata);
            DB::commit();

            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            info('商品入库失败：', $e->getFile() . $e->getLine() . $e->getMessage());
            return throw new \Exception('新增商品入库失败' . $e->getFile() . $e->getLine());
        }
    }

    /**
     *   判定条码是否重复
     *   1. 未审核数据，条码存在入库表，不可入库
     *   2. 未审核数据，删除后，可重新入库
     *   3. 已审核数据，库存表未删除，不可入库
     *   4. 已审核数据，删除库存表，可以入库
     *
     *   params  string goods_sn_code
     *   params  string cp_id
     *   params  string operator  id
     *   return
     */
    public function isRepeatGoodsSnCode($data = [])
    {
        $res = ['code' => '001', 'msg' => ''];
        if (!isset($data['goods_sn_code'])) {
            $res['msg'] = '条码不能为空';
            return $res;
        }
        if (!isset($data['cp_id'])) {
            $res['msg'] = '查询条码数据异常';
            return $res;
        }
        $where[] = ['goods_sn_code', $data['goods_sn_code']];
        $where[] = ['cp_id', $data['cp_id']];
//        $where[] = ['audit_status' => 1];
        if (isset($data['operator']) && isset($data['id'])) {
            $where[] = ['id', '<>', $data['id']];
        }
        //未审核条码已存在，禁止入入库表
        $existUnAuditInfoList = GoodsStockinInfolist::where($where)->where(['audit_status' => 1])->first();
        if ($existUnAuditInfoList) {
            $res['msg'] = '条码：' . $data['goods_sn_code'] . '已存在';
            return $res;
        }
        //已审核条码数据
        $existOnAuditInfoList = GoodsStockinInfolist::where($where)->where(['audit_status' => 2])->first();
        if ($existOnAuditInfoList) {
            $existGoodsStockList = GoodsStockList::where($where)->where(['is_del' => 1])->first();
            if ($existGoodsStockList) {
                $res['msg'] = '条码：' . $data['goods_sn_code'] . '已存在';
                return $res;
            }
        }

        $res['code'] = '000';
        $res['msg'] = '条码正常';
        return $res;
    }

    /**
     * 计算现有商品总成本
     * @param $goods
     * @param $total_netglod_weight
     * @param $count_new
     * @return float
     */
    public function computeTotalCost($goods, $total_netglod_weight, $count_new = 0)
    {
        if ($goods['is_code_more'] == 2) {
            $total_cost_fee = round(($goods['total_cost_fee'] / $goods['total_netglod_weight']) * $total_netglod_weight);
        } else {
            $total_cost_fee = round(($goods['total_cost_fee'] / $goods['count']) * $count_new);
        }
        return $total_cost_fee;
    }


    /**
     * 计算原始总成本
     * @param $goods
     * @param $is_gram
     * @param $isLabel
     * @return float|int
     */
    public function computeOriginalTotalCost($goods, $is_gram = 0)
    {
        $piece_weight = $goods['piece_weight'] ?? 0;
        $netglod_weight = $goods['netglod_weight'] ?? 0;//金重
        $is_code_more = $goods['is_code_more'] ?? 0;//是否一码多货
        //克成本工费
        $costgram_fee = $goods['costgram_fee'] ?? 0;
        //件成本工费
        $costpiece_fee = $goods['costpiece_fee'] ?? 0;
        //单件成本
        $piececost_fee = $goods['piececost_fee'] ?? 0;
        //成本金价
        $costglod_price = $goods['costglod_price'] ?? 0;

        $count = $goods['count'] ?? 0;
        if ($is_code_more == 2) {
            //是一码多货的商品的 总成本=成本金价*总金重
            $total_cost_fee = $costglod_price * $goods['total_netglod_weight'] ?? 0;
        } else {
            // 非一码多货，总金重 =金重*数量
            $total_netglod_weight = $netglod_weight * $count;
            if ($is_gram == 1) {
                //类别是素金和是克算
                //总成本 = （成本金价*总金重+克成本工费*总金重）+件成本工费*数量
                $total_cost_fee = ($costglod_price * $total_netglod_weight + $costgram_fee * $total_netglod_weight) + $costpiece_fee * $count;
            } else {
                if ($piececost_fee <= 0) {
                    //按克成本工费:单件成本=(成本金价+克成本工费)*件重
                    $canFee = $costgram_fee > 0 ? bcmul(($costgram_fee + $costglod_price), $piece_weight, 2) : 0;
                    // 按件成本工费(默认):单件成本=成本金价*件重+件成本工费
                    $pieceFee = $costpiece_fee > 0 ? bcadd($piece_weight * $costglod_price, $costpiece_fee, 2) : 0;
                    if ($costgram_fee > 0 && $costpiece_fee > 0) {
                        $piececost_fee = $pieceFee;
                    } else {
                        $piececost_fee = $canFee > 0 ? $canFee : $pieceFee;
                    }
                }

                //总成本 = 单件成本*数量
                $total_cost_fee = ($piececost_fee * $count);
            }
        }
        return $total_cost_fee ?? 0;
    }


    /**
     * 补货的总成本计算
     * @param $goods
     * @param $replenish
     * @param $is_gram
     * @return array
     */
    public function avgGoodsTotalCost($goods,$replenish, $is_gram = 0)
    {
        $goods_total_cost_fee = $goods['total_cost_fee']??0;
        $replenish_total_cost_fee = $replenish['total_cost_fee']??0;
        $piece_weight =$goods['piece_weight'] ?? 0;
        //库存里的总金重+补货的总金重
        $total_netglod_weight =($goods['total_netglod_weight'] ?? 0)+($replenish['total_netglod_weight'] ?? 0);

       // echo $total_netglod_weight;exit;
        //补货后的总成本=补货时的总成本+库存里的总成本
         $total_cost_fee = $replenish_total_cost_fee+$goods_total_cost_fee;
        //补货后的加权平均成本金价=（库存里的总成本+补货的总成本）/（库存里的总金重+补货的总金重）
        if($total_netglod_weight<=0|| $total_cost_fee<=0){
            $avg_costglod_price=0;
        }else{

            $avg_costglod_price =round(bcdiv($total_cost_fee,$total_netglod_weight,2));
        }

        if($is_gram==1){
            //按克的：
            $piececost_fee=0;
        }else{
            // 按件：
            //补货后的单件成本=件重*补货后的加权成本金价
            $piececost_fee =$piece_weight*$avg_costglod_price;
        }

        // 平均成本金价、平均单件成本、平均总成本
        return [$avg_costglod_price,$piececost_fee,$total_cost_fee];

    }

    /**
     * @param $stock
     * @param $deduction
     * @return array
     *
     *  从库存内出的总成本计算:
     *  例如:
     *  返厂时的总成本=(库存里的总成本/总金重)*返厂总金重
     *  库存里的总成本-调返厂的总成本=库存里剩余的总成本
     *  其他的例如:调拨、销售出库、转旧料等从库存内扣减的都按以上公式计算
     */
    public function deductTotalCost($stock,$deduction)
    {
        info('计算总成本-商品库存数据',$stock);
        info('计算总成本-累减数据',$deduction);

        $total_cost_fee = $stock['total_cost_fee']??0;
        $total_netglod_weight = $stock['total_netglod_weight']??0;
        //返厂时的总成本=库存里的总成本/总金重*返厂总金重

        if($total_cost_fee>0&& $total_netglod_weight>0){
            $deduct_total_cost_fee =($total_cost_fee/$total_netglod_weight)*($deduction['total_netglod_weight']??0);
        }else{
            $deduct_total_cost_fee =0;
        }


        $remaining_cost_fee = $total_cost_fee-$deduct_total_cost_fee;

        return [$deduct_total_cost_fee,$remaining_cost_fee];
    }

    /**
     * @param $stock
     * @param $incr
     * @param $is_gram
     * @return array
     *
     *  类似于返厂后再上柜，销售出库后再撤单，转旧料后再上柜等的场景库存内总成本及成本金价的计算:
     *  按克的:
     *  总成本=返厂时的总成本+库存里的总成本
     *  成本金价=(返厂时的总成本+库存里的总成本)/(返厂时的总金重+库存里的总金重)
     *  按件的:
     *  总成本=返厂时的总成本+库存里的总成本
     *  成本金价=(返厂时的总成本+库存里的总成本)/(返厂时的总金重+库存里的总金重)
     *  单件成本=件重*成本金价
     */
    public function incrTotalCost($stock,$incr,$is_gram=0)
    {
       info('计算总成本-商品库存数据',$stock);
       info('计算总成本-累加数据',$incr);
        //总成本=当时操作的总成本+库存里的总成本
        $total_cost_fee = ($incr['total_cost_fee']??0)+($stock['total_cost_fee']??0);

        //成本金价=(返厂时的总成本+库存里的总成本)/(返厂时的总金重+库存里的总金重)
        $total_netglod_weight = ($incr['total_netglod_weight']??0)+($stock['total_netglod_weight']??0);
        $costglod_price =0;
        if($total_cost_fee>0&& $total_netglod_weight>0){
            $costglod_price =bcdiv($total_cost_fee,$total_netglod_weight);
        }

        // 单件成本
        $piececost_fee =0;
        if($is_gram==2){
             // 按件的：单件成本=件重*成本金价
            $piececost_fee =bcmul(($stock['piece_weight']??0),$costglod_price,3);
        }

        return [$total_cost_fee,$costglod_price,$piececost_fee];

    }


    /**
     * 检查商品和订单某一个字段是否存在数据
     * @param $key
     * @param $value
     * @return bool
     */
    public function  checkGoods($key,$value)
    {
        $goodsExists =GoodsStockList::query()
            ->where("$key",$value)
            ->where("is_del",1)
            ->value('id');

        $orderExists =OrderSalesGoods::query()
            ->where("$key",$value)
            ->value('id');

        $stockinExists =GoodsStockinInfolist::query()
            ->where("$key",$value)
            ->value('id');

        if(!empty($goodsExists)|| !empty($orderExists)||!empty($stockinExists)){
            return true;
        }else{
            return  false;
        }
    }




    /**
     * 记录商品日志
     * @param $accountinfo
     * @param int $start_store_id
     * @param int $target_store_id
     * @param array $goodsinfo
     * @param int $count
     * @param int $log_type
     * @param $with_sn_code
     * @return void
     */
    public  function addGoodLogs($accountinfo, int $start_store_id, int $target_store_id, array $goodsinfo, int $count, int $log_type, $with_sn_code = '')
    {
        $cp_id = $accountinfo['cp_id'];
        $start_store_id = $start_store_id > 0 ? $start_store_id : intval($accountinfo['store_ids'] ?? 0);

        if (in_array($log_type, [1, 2])) {
            $start_store_id = 0;
        } elseif (in_array($log_type, [21, 23, 5])) {
            $target_store_id = 0;
        }

        $data = [
            'cp_id' => $cp_id,
            'start_store_id' => $start_store_id,
            'target_store_id' => $target_store_id,
            'goods_img' => isset($goodsinfo['goods_img']) ? $goodsinfo['goods_img'] : '',
            'goods_sn_code' => $goodsinfo['goods_sn_code'],
            'goods_name' => $goodsinfo['goods_name'] ?? '',
            'goods_category_id' => $goodsinfo['goods_category_id']??0,
            'cf_no' => isset($goodsinfo['cf_no']) ? $goodsinfo['cf_no'] : '',
            'count' => $count,
            'piece_weight' => isset($goodsinfo['piece_weight']) ? $goodsinfo['piece_weight'] : 0,
            'netglod_weight' => (isset($goodsinfo['is_code_more']) && $goodsinfo['is_code_more'] == 2) ? (isset($goodsinfo['total_netglod_weight']) ? $goodsinfo['total_netglod_weight'] : 0) : (isset($goodsinfo['netglod_weight']) ? $goodsinfo['netglod_weight'] : 0),
            'label_price' => isset($goodsinfo['label_price']) ? $goodsinfo['label_price'] : 0,
            'piececost_fee' => isset($goodsinfo['piececost_fee']) ? $goodsinfo['piececost_fee'] : 0,
            'log_type' => $log_type,
            'with_sn_code' => $with_sn_code,
            'stockin_at' => $goodsinfo['stockin_at']??0,
            'create_account_id' => $accountinfo['id'],
            'create_account_real_name' => $accountinfo['real_name'],
            'create_at' => time(),
            'update_at' => time(),
            'is_code_more' => isset($goodsinfo['is_code_more']) ? $goodsinfo['is_code_more'] : 1,
            'costgram_fee' => $goodsinfo['costgram_fee'] ?? 0,
            'costpiece_fee' => $goodsinfo['costpiece_fee'] ?? 0,
            'costglod_price' => $goodsinfo['costglod_price'] ?? 0,
            'total_cost_fee'=>$goodsinfo['total_cost_fee'] ?? 0,
        ];

        info('商品流水' . $log_type, $data);
        GoodsLog::query()->create($data);
    }


}
